package com.jacobson.huobi.mvp

import android.content.Context
import android.content.Intent
import android.graphics.BitmapFactory
import android.os.Build
import android.os.Bundle
import android.util.Base64
import android.widget.Toast
import com.alibaba.fastjson.JSONObject
import com.jacobson.core.base.Immersive
import com.jacobson.core.di.components.AppComponent
import com.jacobson.core.di.modules.ActivityModule
import com.jacobson.core.mvp.BaseMvpActivity
import com.jacobson.huobi.Constants
import com.jacobson.huobi.R
import com.jacobson.huobi.di.components.DaggerEditPasswordActivityComponent
import com.jacobson.huobi.di.modules.EditPasswordActivityModule
import com.jacobson.huobi.entities.events.LoginEvent
import com.jacobson.huobi.entities.evt.UpdPwdEvt
import com.jacobson.huobi.entities.response.CommonResponse
import com.jacobson.huobi.entities.response.LoginPageResponse
import com.jacobson.huobi.entities.vo.LoginRespVo
import com.jacobson.huobi.mvp.contract.EditPasswordContract
import com.jacobson.huobi.mvp.fragment.SymbolFragment
import com.jacobson.huobi.threads.TokenThread
import com.jacobson.huobi.utils.*
import kotlinx.android.synthetic.main.activity_edit_password.*
import kotlinx.android.synthetic.main.activity_edit_password.btnBack
import kotlinx.android.synthetic.main.activity_login.*
import org.simple.eventbus.EventBus
import java.util.regex.Pattern

@Immersive(fitSystemWindows = false)
class EditPasswordActivity :
    BaseMvpActivity<EditPasswordContract.Presenter>(), EditPasswordContract.View {


    var loginRespVo: LoginRespVo? = null

    private lateinit var timer: VertiCodeTimer

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        //修改底部功能键背景色 只支持api为21及以上
        if (Build.VERSION.SDK_INT  >= Build.VERSION_CODES.LOLLIPOP) {
            window.navigationBarColor = ResourcesUtil.getColor(R.color.colorPrimary) //设定底部导航栏  同全局颜色
        }
    }
    override fun setupActivityComponent(appComponent: AppComponent) {
        DaggerEditPasswordActivityComponent.builder()
            .editPasswordActivityModule(EditPasswordActivityModule(this))
            .appComponent(appComponent)
            .activityModule(ActivityModule(this))
            .build()
            .inject(this)
    }

    override fun initView(savedInstanceState: Bundle?): Int = R.layout.activity_edit_password

    override fun initData(savedInstanceState: Bundle?) {

        timer = VertiCodeTimer(60000, 1000, btnUpdPwdRefreshCaptcha)

        initBtnClick()
        initFocus()
    }

    /**
     * 更新密码响应
     */
    override fun onUpdatePwdResultResp(response: CommonResponse<JSONObject>) {
        if (response.code == Constants.RESP_OK) {
            presenter.logout()
            Toast.makeText(this, "修改成功,请重新登录", Toast.LENGTH_SHORT).show()
        }else {
            Toast.makeText(this, response.msg, Toast.LENGTH_SHORT).show()
        }
    }

    /**
     * 登出响应
     */
    override fun onLogoutResultResp(response: CommonResponse<JSONObject>) {
        TokenThread.stop()
        TokenStorageUtil.save("")
        EventBus.getDefault().post(LoginEvent(1, null))
        MainActivity.startHomeActivity(this, SymbolFragment.ME)
    }

    override fun onVertiCodeResultResp(response: LoginPageResponse) {
        if (response.code == Constants.RESP_OK) {
            Toast.makeText(this,"发送短信成功",Toast.LENGTH_SHORT).show()
        } else {
            Toast.makeText(this, response.msg, Toast.LENGTH_SHORT).show()
        }    }


    override fun onError(type: Int, extra: Any?, code: Int, message: String): Boolean {
        logger.e("error >>> $message")
        return super.onError(type, extra, code, message)
    }

    private fun initBtnClick() {

        btnBack.setOnClickListener {
            this.finish()
        }

        btnEditPwd.setOnClickListener {
            editPwd()
        }

        btnUpdPwdRefreshCaptcha.setOnClickListener{
            var phoneNumber = etUpdPwdPhoneNumber.text.trim().toString()
//            loginRespVo = TokenStorageUtil.read()
//            val phoneNumber = loginRespVo!!.telephone
            if (phoneNumber.isBlank()) {
                Toast.makeText(this, "手机号不能为空", Toast.LENGTH_SHORT).show()
            } else {
                if (checkPhoneNum(phoneNumber)) {
                    presenter.getVertiCode(phoneNumber)
                    timer.start()
                } else {
                    Toast.makeText(this, "手机号码非法", Toast.LENGTH_SHORT).show()
                }

            }
        }
    }

    /**
     * 修改密码
     */
    private fun editPwd() {
//        var oldPwd = etOldPwd.text.trim().toString()
        var newPwd = etNewPwd.text.trim().toString()
        var repeatNewPwd = etRepeatNewPwd.text.trim().toString()
        val captcha = etUpdPwdCaptcha.text.trim().toString()
        var phoneNumber = etUpdPwdPhoneNumber.text.trim().toString()
//            loginRespVo = TokenStorageUtil.read()
//            val phoneNumber = loginRespVo!!.telephone


        if (phoneNumber.isNullOrBlank()) {
            Toast.makeText(this, "手机号不能为空", Toast.LENGTH_SHORT).show()
        }
//        if (oldPwd.isNullOrBlank()) {
//            Toast.makeText(this, "旧密码不能为空", Toast.LENGTH_SHORT).show()
//            return
//        }
        if (newPwd.isNullOrBlank()) {
            Toast.makeText(this, "新密码不能为空", Toast.LENGTH_SHORT).show()
            return
        }else {
            if (!DataUtil.isLetterDigit(newPwd) || newPwd.length < 8) {
                Toast.makeText(this, "密码至少8位且必须包含英文和数字", Toast.LENGTH_SHORT).show()
                return
            }
        }
        if (repeatNewPwd.isNullOrBlank()) {
            Toast.makeText(this, "确认密码不能为空", Toast.LENGTH_SHORT).show()
            return
        }
        if (captcha.isNullOrBlank()) {
            Toast.makeText(this, "验证码不能为空", Toast.LENGTH_SHORT).show()
            return
        }
//        var enOldPwd :String = EncryptUtil.encrypData(oldPwd, captcha)
        var enNewPwd :String = EncryptUtil.encrypData(newPwd, captcha)
//        if (enOldPwd.isNullOrBlank()) {
//            Toast.makeText(this, "旧密码加密失败", Toast.LENGTH_SHORT).show()
//            return
//        }
        if (enNewPwd.isNullOrBlank()) {
            Toast.makeText(this, "新密码加密失败", Toast.LENGTH_SHORT).show()
            return
        }

        presenter.updatePwd(UpdPwdEvt( new_pwd = enNewPwd, captcha = captcha, telephone = phoneNumber))

    }

    /**
     * 初始化焦点事件
     */
    private fun initFocus() {
        etNewPwd.setOnFocusChangeListener { _, b ->
            if (!b) {
                var newPwd = etNewPwd.text.trim().toString()
                if (!DataUtil.isLetterDigit(newPwd) || newPwd.length < 8) {
                    Toast.makeText(this, "密码至少8位且必须包含英文和数字", Toast.LENGTH_SHORT).show()
                }
            }
        }

        etRepeatNewPwd.setOnFocusChangeListener { _, b ->
            if (!b) {
                var newPwd = etNewPwd.text.trim().toString()
                var repeatNewPwd = etRepeatNewPwd.text.trim().toString()
                if (newPwd != repeatNewPwd) {
                    Toast.makeText(this, "两次输入的密码不一样", Toast.LENGTH_SHORT).show()
                }
            }
        }
    }

    /***
     * 手机号码检测
     */
    private fun checkPhoneNum(num: String): Boolean {
        val regExp = "^((13[0-9])|(15[^4])|(18[0-9])|(17[0-8])|(14[5-9])|(166)|(19[8,9])|)\\d{8}$"
        val p = Pattern.compile(regExp)
        val m = p.matcher(num)
        return m.matches()
    }


    companion object {
        fun startActivity(context: Context) {
            Intent(context, EditPasswordActivity::class.java).run {
                context.startActivity(this)
            }
        }

    }

}
